﻿// <copyright>
// Project: sofort.NET
// Date:  2014 - 02 - 04
// Copyright: Karl Haak 2014
// </copyright>
// <author>Karl Haak (www.karlhaak.de)</author>
using System;
using System.IO;
using System.Reflection;
using System.Xml.Serialization;

namespace pay.sofort
{
    public class TPaySofortConfig
    {
        #region ### Properties

        public string Username { get; set; }
        public string ConnectionString { get; set; }

        public string Konfigurationsschluessel { get; set; }

        public string Kundennummer
        {
            get { return Konfigurationsschluessel.Split(':')[0]; }
        }

        public int ProjectId
        {
            get { return Convert.ToInt32(Konfigurationsschluessel.Split(':')[1]); }
        }

        public string ApiKey
        {
            get { return Konfigurationsschluessel.Split(':')[2]; }
        }

        public string SofortUeberweisungUrl { get; set; }

        public string SuccessUrl { get; set; }
        public string AbortUrl { get; set; }
        public string TimeoutUrl { get; set; }

        public string Notification_url_1 { get; set; }
        public string Notification_url_1_notify_on { get; set; }
        public string Notification_url_2 { get; set; }
        public string Notification_url_2_notify_on { get; set; }

        #endregion

        #region ### Ctor ###

        public TPaySofortConfig()
        {
            SofortUeberweisungUrl = "https://api.sofort.com/api/xml";
            Username = "Sofort.NET";
        }

        #endregion

        #region ### Private ###

        private static TPaySofortConfig Read(string fullFilePath)
        {
            var reader =
                new XmlSerializer(typeof (TPaySofortConfig));
            TPaySofortConfig config;
            using (var file = new StreamReader(fullFilePath))
            {
                config = (TPaySofortConfig) reader.Deserialize(file);
            }

            return config;
        }

        #endregion

        #region ### Methods ###

        public void WriteToFile(string fullFilePath)
        {
            var x = new XmlSerializer(GetType());
            using (var file = new StreamWriter(fullFilePath))
            {
                x.Serialize(file, this);
            }
        }

        public static TPaySofortConfig LoadFromFile(string fullFileName = "")
        {
            if (String.IsNullOrWhiteSpace(fullFileName))
            {
                string baseDir = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);
                fullFileName = Path.Combine(baseDir, "sofort.xml");
            }

            if (File.Exists(fullFileName))
                return Read(fullFileName);
            throw new FileNotFoundException(fullFileName);
        }

        #endregion
    }
}